<?php

class PersonDateController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
//            array('allow', // allow all users to perform 'index' and 'view' actions
//                'actions' => array('index', 'view'),
//                'users' => array('*'),
//            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('index', 'view', 'create', 'update', 'assignTask', 'popCreateFromTemplate', 'assignTemplate', 'templateInt', 'popCreateFromTemplateSave', 'doneJob', 'otherAdmin', 'delete'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin'),
                'users' => User::model()->getUsers(1),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $searchModel = new PersonTask('search');
        $searchModel->unsetAttributes();  // clear any default values
        if (isset($_GET['PersonTask'])) {
            $searchModel->attributes = $_GET['PersonTask'];
        }
        $this->render('view', array(
            'model' => $this->loadModel($id),
            'searchModel' => $searchModel,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new PersonDate;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['PersonDate'])) {
            $model->attributes = $_POST['PersonDate'];
            if ($model->save()) {
                $this->redirect(array('assignTask', 'id' => $model->pdid));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['PersonDate'])) {
            $model->attributes = $_POST['PersonDate'];
//            var_dump($_POST['PersonDate']);
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->pdid));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
//        $dataProvider = new CActiveDataProvider('PersonDate');
//        $this->render('index', array(
//            'dataProvider' => $dataProvider,
//        ));
        $this->actionAdmin();
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new PersonDate('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['PersonDate'])) {
            $model->attributes = $_GET['PersonDate'];
        }
        $jobStatus = (int) $_REQUEST['s'];
        switch ($jobStatus) {
            case 0:
                $title = 'Todo List';
                break;
            case 1:
                $title = 'Completed List';
                break;
            case 100:
                $title = 'Template List';
                break;
            default :
                $title = 'Todo List';
        }
        $this->render('admin', array(
            'model' => $model,
            'jobStatus' => $jobStatus,
            'title' => $title,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionOtherAdmin() {
        $model = new PersonDate('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['PersonDate'])) {
            $model->attributes = $_GET['PersonDate'];
        }
        $jobStatus = (int) $_REQUEST['s'];
        $this->render('otherAdmin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = PersonDate::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'person-date-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionAssignTask($id) {        
        $searchModel = new Task('search');
        $searchModel->unsetAttributes();  // clear any default values
        if (isset($_GET['Task'])) {
            $searchModel->attributes = $_GET['Task'];
        }
        
        $searchTaskModel = new PersonTask('search');
        $searchTaskModel->unsetAttributes();  // clear any default values
        if (isset($_GET['PersonTask'])) {
            $searchTaskModel->attributes = $_GET['PersonTask'];
        }
       
        $this->render('assign', array(
            'model' => $this->loadModel($id),
            'searchModel' => $searchModel,
            'searchTaskModel' => $searchTaskModel,
        ));
    }

    //从模板创建Job初始化
    public function actionTemplateInt($id) {
        $model = $this->loadModel($id);
        $templateTid = array();
        foreach ($model->tasks as $task) {
            $templateTid[] = $task['tid'];
        }
        if ($templateTid) {
            $session = Yii::app()->session;
            $session['templateTid'] = $templateTid;
        }
        $this->actionPopCreateFromTemplate($id);
    }

    //从模板创建Job
    public function actionPopCreateFromTemplate($id) {
        $session = Yii::app()->session;
        $idArr = $session['templateTid'];

        $this->layout = 'pop';
        $model = $this->loadModel($id);

        $searchModel = new Task('search');
        $searchModel->unsetAttributes();  // clear any default values
        if (isset($_GET['Task'])) {
            $searchModel->attributes = $_GET['Task'];
        }


        $searchTaskModel = new Task('search');
        $searchTaskModel->unsetAttributes();  // clear any default values
        if (isset($_GET['Task'])) {
            $searchTaskModel->attributes = $_GET['Task'];
        }

        $this->render('popCreate', array(
            'model' => $model,
            'searchModel' => $searchModel,
            'searchTaskModel' => $searchTaskModel,
            'idArr' => $idArr,
        ));
    }

    //从template创建job的保存function
    public function actionPopCreateFromTemplateSave() {
        $this->layout = 'pop';
        if ($_POST['Task']) {
            if (is_numeric($_POST['Task']['parent']) && $_POST['TaskTime']) {
                $session = Yii::app()->session;
                $idArr = $session['templateTid'];

                $templateModel = $this->loadModel($_POST['Task']['parent']);
                $model = new PersonDate;
                $model->type = $templateModel->type;
                $model->style = $templateModel->style;
                $model->parent = $templateModel->pdid;
                $model->time = $_POST['TaskTime'];

                if ($model->save()) {
                    //开始增加属于Job的task
                    foreach ($idArr as $idItem) {
                        $task = Task::model()->find('taskid=:taskID', array('taskID' => (int) $idItem));
                        $personTaskModel = new PersonTask;
                        $personTaskModel->pdid = $model->pdid;
                        $personTaskModel->tid = $idItem;
                        $personTaskModel->total_complete = $task->complete;
                        $personTaskModel->save();
                        unset($personTaskModel);
                    }
                    $result['result'] = true;
//                    $this->redirect(array('view', 'id' => $model->pdid));
                } else {
                    $result['result'] = false;
                    $result['msg'] = '创建失败，请记录详细的操作步骤，并通知TBI7';
                }
            } else {
                $result['result'] = false;
                $result['msg'] = '创建失败，模板不存在或者未输入Time，请检查';
            }
        }
        $this->render('popCreateDone', array(
            'model' => $model,
            'result' => $result,
        ));
    }

    //从template创建job时，组成临时任务的idarr
    public function actionAssignTemplate() {
        $session = Yii::app()->session;
        $idArr = $session['templateTid'];
        if ($_POST['taskSelect']) {
            foreach ($_POST['taskSelect'] as $taskSelect) {
                $idArr[] = $taskSelect;
            }
            $session['templateTid'] = array_unique($idArr);
        } elseif ($_POST['taskDelete']) {
            $session['templateTid'] = array_diff($idArr, $_POST['taskDelete']);
        }
        echo CJSON::encode(array('success' => true));
    }

    //job关闭函数，需要判断job下的personTask是否都关闭了
    public function actionDoneJob() {
        if (Yii::app()->request->isPostRequest) {
            $jobIdArr = $_POST['jobSelect'];
            foreach ($jobIdArr as $jobId) {
                $unDoneTasks = PersonTask::model()->findJobTask(0, $jobId); //搜索本job的未完成persontask
                $sucess = true;
                if ($unDoneTasks) {
                    //自动关闭未完成的任务
                    foreach ($unDoneTasks as $unDoneTask) {
                        $unDoneTask->today_extra = 0;
                        $unDoneTask->time_spent = 0;
                        $unDoneTask->status = 1;
                        $sucess = $unDoneTask->save();
                        if (!$sucess)
                            break;
                    }
                }

                if ($sucess) {//没有未完成的personTask，可以正常结束
                    $job = $this->loadModel($jobId);
                    if ($job->status == 0) {
                        $job->status = 1;
                        if ($job->save()) {
                            $msg .= 'Job(' . $jobId . '): 已经关闭.
';
                        } else {
                            $msg .= 'Job(' . $jobId . '): 关闭时发生错误.
';
                        }
                    } else {
                        $msg .= 'Job(' . $jobId . '): 不是正在进行中的任务，不需要关闭.
';
                    }
                } else {
                    $msg .= 'Job(' . $jobId . '): 有未完成的任务,未成功关闭，请检查.
';
                }
            }
            echo CJSON::encode(array('success' => true, 'msg' => $msg));
        }
    }
}

